package com.lzc.ai.controller;

import com.lzc.ai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

/**
 * @author lizhichuan
 * @description: TODO
 * @date 2025/5/24 23:56
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    @Autowired
    private ChatClient chatClient;

    @Autowired
    private ChatHistoryRepository chatHistoryRepository;

    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chat(@RequestParam("prompt") String prompt){
        return chatClient.prompt().user(prompt).stream().content();
    }

    /**
     * 会话记忆
     *
     * @param prompt
     * @param chatId
     * @return
     */
    @RequestMapping(value = "/chat1", produces = "text/html;charset=utf-8")
    public Flux<String> chat1(@RequestParam("prompt") String prompt
                            , @RequestParam("chatId")String chatId){
        //保存会话id
        chatHistoryRepository.save("chat", chatId);
        return chatClient.prompt()
                 .user(prompt)
                 .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))//添加会话id到AdvisorContext
                 .stream()
                 .content();
     }




}
